package com.moke.xlsx
{
	import flash.utils.ByteArray;
	
	/**
	 * 解析Excel2007(xlsx)文件
	 * @author tb
	 * 
	 */	
	public class Excel2007
	{
		private var _xlsx:XlsxFile;
		private var _sheets:Array = [];
		
		public function Excel2007()
		{
			
		}
		
		/**
		 * 取得解析后的表格列表，表格数据为二维数组，第一维是行索引，第二维是列索引
		 * @return 
		 * 
		 */		
		public function get sheets():Array
		{
			return _sheets;
		}
		
		public function set data(value:ByteArray):void
		{
			if(value == null)
			{
				return ;
			}
			if (_xlsx == null)
			{
				_xlsx = new XlsxFile();
			}
			_xlsx.data = value;
			//
			var sharedStrings:Array = XMLUtil.getSharedStrings(_xlsx.getFile(XlsxFile.sharedStringsURL));
			_sheets = XMLUtil.getSheetListFromWorkbook(_xlsx.getFile(XlsxFile.workbookURL));
			for each(var sheet:Sheet in _sheets)
			{
				parseSheet(sheet,sharedStrings);
			}
		}
		
		private function parseSheet(sheet:Sheet,sharedStrings:Array):void
		{
			var bytes:ByteArray = _xlsx.getFile(XlsxFile.getSheetURL(sheet.id));
			var xml:XML = XML(bytes.readUTFBytes(bytes.bytesAvailable));
			var ns:Namespace = xml.namespace();
			var dimension:XML = xml.ns::dimension[0];
			var refArr:Array = String(dimension.@ref).split(":");
			if(refArr.length < 2)
			{
				return ;
			}
			sheet.startRow = ExcelUtil.getInt(refArr[0]);
			sheet.endRow = ExcelUtil.getInt(refArr[1]);
			sheet.startCol = ExcelUtil.getLetter(refArr[0]);
			sheet.endCol = ExcelUtil.getLetter(refArr[1]);
			//
			XMLUtil.parseRow(sheet.values,xml.ns::sheetData.ns::row, ns, sharedStrings);
			XMLUtil.mergeCell(sheet.values,xml.ns::mergeCells.ns::mergeCell);
		}
		
		public function dispose():void
		{
			_xlsx.dispose();
			_xlsx = null;
			_sheets = null;
		}
		
	}
}